/**
 * 多端兼容性工具
 * 提供平台检测、API适配和条件编译支持
 */

// 平台类型枚举
export enum PlatformType {
  H5 = 'h5',
  MP_WEIXIN = 'mp-weixin',
  MP_TOUTIAO = 'mp-toutiao',
  MP_XHS = 'mp-xhs',
  MP_ALIPAY = 'mp-alipay',
  MP_BAIDU = 'mp-baidu',
  MP_QQ = 'mp-qq',
  APP_PLUS = 'app-plus',
  QUICKAPP = 'quickapp',
  UNKNOWN = 'unknown'
}

// 平台能力接口
export interface PlatformCapabilities {
  supportCamera: boolean;
  supportLocation: boolean;
  supportPush: boolean;
  supportPayment: boolean;
  supportShare: boolean;
  supportStorage: boolean;
  supportWebview: boolean;
  supportBluetooth: boolean;
  supportNFC: boolean;
  maxImageSize: number; // MB
  maxVideoSize: number; // MB
}

/**
 * 平台兼容性管理器
 */
export class PlatformManager {
  private static instance: PlatformManager;
  private currentPlatform: PlatformType;
  private capabilities: PlatformCapabilities;
  
  private constructor() {
    this.currentPlatform = this.detectPlatform();
    this.capabilities = this.getPlatformCapabilities();
    this.logPlatformInfo();
  }
  
  static getInstance(): PlatformManager {
    if (!this.instance) {
      this.instance = new PlatformManager();
    }
    return this.instance;
  }
  
  /**
   * 检测当前平台
   */
  private detectPlatform(): PlatformType {
    // #ifdef H5
    return PlatformType.H5;
    // #endif
    
    // #ifdef MP-WEIXIN
    return PlatformType.MP_WEIXIN;
    // #endif
    
    // #ifdef MP-TOUTIAO
    return PlatformType.MP_TOUTIAO;
    // #endif
    
    // #ifdef MP-XHS
    return PlatformType.MP_XHS;
    // #endif
    
    // #ifdef MP-ALIPAY
    return PlatformType.MP_ALIPAY;
    // #endif
    
    // #ifdef MP-BAIDU
    return PlatformType.MP_BAIDU;
    // #endif
    
    // #ifdef MP-QQ
    return PlatformType.MP_QQ;
    // #endif
    
    // #ifdef APP-PLUS
    return PlatformType.APP_PLUS;
    // #endif
    
    // #ifdef QUICKAPP
    return PlatformType.QUICKAPP;
    // #endif
    
    return PlatformType.UNKNOWN;
  }
  
  /**
   * 获取平台能力
   */
  private getPlatformCapabilities(): PlatformCapabilities {
    const baseCapabilities: PlatformCapabilities = {
      supportCamera: true,
      supportLocation: true,
      supportPush: false,
      supportPayment: false,
      supportShare: true,
      supportStorage: true,
      supportWebview: false,
      supportBluetooth: false,
      supportNFC: false,
      maxImageSize: 10, // 10MB
      maxVideoSize: 100 // 100MB
    };
    
    switch (this.currentPlatform) {
      case PlatformType.H5:
        return {
          ...baseCapabilities,
          supportPush: true,
          supportWebview: true,
          supportBluetooth: true,
          supportNFC: true,
          maxImageSize: 50,
          maxVideoSize: 500
        };
        
      case PlatformType.MP_WEIXIN:
        return {
          ...baseCapabilities,
          supportPayment: true,
          supportShare: true,
          supportWebview: true,
          maxImageSize: 20,
          maxVideoSize: 200
        };
        
      case PlatformType.MP_TOUTIAO:
        return {
          ...baseCapabilities,
          supportShare: true,
          maxImageSize: 15,
          maxVideoSize: 150
        };
        
      case PlatformType.APP_PLUS:
        return {
          ...baseCapabilities,
          supportPush: true,
          supportPayment: true,
          supportWebview: true,
          supportBluetooth: true,
          supportNFC: true,
          maxImageSize: 100,
          maxVideoSize: 1000
        };
        
      default:
        return baseCapabilities;
    }
  }
  
  /**
   * 记录平台信息
   */
  private logPlatformInfo(): void {
    console.group('🔧 平台兼容性信息');
    console.log('当前平台:', this.currentPlatform);
    console.log('平台能力:', this.capabilities);
    console.groupEnd();
  }
  
  /**
   * 获取当前平台
   */
  getCurrentPlatform(): PlatformType {
    return this.currentPlatform;
  }
  
  /**
   * 获取平台能力
   */
  getCapabilities(): PlatformCapabilities {
    return { ...this.capabilities };
  }
  
  /**
   * 检查是否支持某项能力
   */
  isSupported(capability: keyof PlatformCapabilities): boolean {
    const value = this.capabilities[capability];
    return typeof value === 'boolean' ? value : value > 0;
  }
  
  /**
   * 是否为小程序平台
   */
  isMiniProgram(): boolean {
    return [
      PlatformType.MP_WEIXIN,
      PlatformType.MP_TOUTIAO,
      PlatformType.MP_XHS,
      PlatformType.MP_ALIPAY,
      PlatformType.MP_BAIDU,
      PlatformType.MP_QQ
    ].includes(this.currentPlatform);
  }
  
  /**
   * 是否为移动端
   */
  isMobile(): boolean {
    return this.currentPlatform !== PlatformType.H5 || this.isMobileH5();
  }
  
  /**
   * 是否为移动端H5
   */
  private isMobileH5(): boolean {
    // #ifdef H5
    if (typeof navigator !== 'undefined') {
      return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }
    // #endif
    return false;
  }
  
  /**
   * 获取平台特定的API调用
   */
  getPlatformAPI() {
    return {
      /**
       * 选择图片
       */
      chooseImage: (options: any) => {
        if (this.isSupported('supportCamera')) {
          return uni.chooseImage({
            ...options,
            count: Math.min(options.count || 1, this.isMiniProgram() ? 9 : 1)
          });
        } else {
          return Promise.reject(new Error('当前平台不支持选择图片'));
        }
      },
      
      /**
       * 获取位置信息
       */
      getLocation: (options: any) => {
        if (this.isSupported('supportLocation')) {
          return uni.getLocation(options);
        } else {
          return Promise.reject(new Error('当前平台不支持获取位置'));
        }
      },
      
      /**
       * 分享功能
       */
      share: (options: any) => {
        if (this.isSupported('supportShare')) {
          // #ifdef MP-WEIXIN
          return uni.showShareMenu(options);
          // #endif
          
          // #ifdef H5
          if (navigator.share) {
            return navigator.share(options);
          } else {
            // 降级处理：复制链接
            return this.copyToClipboard(options.url || window.location.href);
          }
          // #endif
          
          return Promise.resolve();
        } else {
          return Promise.reject(new Error('当前平台不支持分享'));
        }
      },
      
      /**
       * 支付功能
       */
      payment: (options: any) => {
        if (this.isSupported('supportPayment')) {
          // #ifdef MP-WEIXIN
          return uni.requestPayment(options);
          // #endif
          
          // #ifdef APP-PLUS
          return uni.requestPayment(options);
          // #endif
          
          return Promise.reject(new Error('当前平台支付功能开发中'));
        } else {
          return Promise.reject(new Error('当前平台不支持支付'));
        }
      },
      
      /**
       * 推送通知
       */
      notification: (options: any) => {
        if (this.isSupported('supportPush')) {
          // #ifdef H5
          if ('Notification' in window) {
            return Notification.requestPermission().then(permission => {
              if (permission === 'granted') {
                new Notification(options.title, {
                  body: options.content,
                  icon: options.icon
                });
              }
            });
          }
          // #endif
          
          // #ifdef APP-PLUS
          return uni.createPushMessage(options);
          // #endif
          
          return Promise.resolve();
        } else {
          return Promise.reject(new Error('当前平台不支持推送通知'));
        }
      }
    };
  }
  
  /**
   * 复制到剪贴板
   */
  private copyToClipboard(text: string): Promise<void> {
    return new Promise((resolve, reject) => {
      // #ifdef H5
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(resolve).catch(reject);
      } else {
        // 降级处理
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        try {
          document.execCommand('copy');
          resolve();
        } catch (err) {
          reject(err);
        } finally {
          document.body.removeChild(textArea);
        }
      }
      // #endif
      
      // #ifndef H5
      uni.setClipboardData({
        data: text,
        success: () => resolve(),
        fail: reject
      });
      // #endif
    });
  }
  
  /**
   * 获取平台特定的样式
   */
  getPlatformStyles() {
    const baseStyles = {
      statusBarHeight: 0,
      navigationBarHeight: 44,
      tabBarHeight: 50,
      safeAreaBottom: 0
    };
    
    // #ifdef H5
    return {
      ...baseStyles,
      statusBarHeight: 0,
      navigationBarHeight: 0, // H5通常不需要导航栏
      tabBarHeight: 60
    };
    // #endif
    
    // #ifdef MP-WEIXIN
    const wxSystemInfo = uni.getSystemInfoSync();
    return {
      ...baseStyles,
      statusBarHeight: wxSystemInfo.statusBarHeight || 20,
      navigationBarHeight: 44,
      safeAreaBottom: wxSystemInfo.safeAreaInsets?.bottom || 0
    };
    // #endif
    
    // #ifdef APP-PLUS
    const appSystemInfo = uni.getSystemInfoSync();
    return {
      ...baseStyles,
      statusBarHeight: appSystemInfo.statusBarHeight || 20,
      safeAreaBottom: appSystemInfo.safeAreaInsets?.bottom || 0
    };
    // #endif
    
    return baseStyles;
  }
  
  /**
   * 检查文件大小限制
   */
  checkFileSize(fileSize: number, fileType: 'image' | 'video'): boolean {
    const maxSize = fileType === 'image' 
      ? this.capabilities.maxImageSize 
      : this.capabilities.maxVideoSize;
    
    const fileSizeMB = fileSize / (1024 * 1024);
    return fileSizeMB <= maxSize;
  }
  
  /**
   * 获取平台特定的配置
   */
  getPlatformConfig() {
    return {
      platform: this.currentPlatform,
      isMiniProgram: this.isMiniProgram(),
      isMobile: this.isMobile(),
      capabilities: this.capabilities,
      styles: this.getPlatformStyles(),
      api: this.getPlatformAPI()
    };
  }
}

/**
 * 平台适配装饰器
 */
export function platformAdapt(platforms: PlatformType[]) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    const platformManager = PlatformManager.getInstance();
    
    descriptor.value = function (...args: any[]) {
      if (platforms.includes(platformManager.getCurrentPlatform())) {
        return originalMethod.apply(this, args);
      } else {
        console.warn(`方法 ${propertyKey} 在当前平台 ${platformManager.getCurrentPlatform()} 不支持`);
        return Promise.reject(new Error(`当前平台不支持此功能`));
      }
    };
    
    return descriptor;
  };
}

/**
 * 条件编译辅助函数
 */
export const platform = {
  isH5: () => PlatformManager.getInstance().getCurrentPlatform() === PlatformType.H5,
  isMiniProgram: () => PlatformManager.getInstance().isMiniProgram(),
  isApp: () => PlatformManager.getInstance().getCurrentPlatform() === PlatformType.APP_PLUS,
  isWeixin: () => PlatformManager.getInstance().getCurrentPlatform() === PlatformType.MP_WEIXIN,
  isToutiao: () => PlatformManager.getInstance().getCurrentPlatform() === PlatformType.MP_TOUTIAO,
  isMobile: () => PlatformManager.getInstance().isMobile()
};

/**
 * 获取平台管理器实例
 */
export const getPlatformManager = () => PlatformManager.getInstance();

/**
 * 平台兼容性检查
 */
export function checkPlatformCompatibility(): {
  compatible: boolean;
  issues: string[];
  recommendations: string[];
} {
  const manager = PlatformManager.getInstance();
  const platform = manager.getCurrentPlatform();
  const capabilities = manager.getCapabilities();
  
  const issues: string[] = [];
  const recommendations: string[] = [];
  
  // 检查基本功能支持
  if (!capabilities.supportCamera) {
    issues.push('不支持相机功能');
    recommendations.push('考虑提供文件上传替代方案');
  }
  
  if (!capabilities.supportLocation) {
    issues.push('不支持定位功能');
    recommendations.push('考虑手动输入位置信息');
  }
  
  if (!capabilities.supportPayment) {
    issues.push('不支持支付功能');
    recommendations.push('引导用户到支持支付的平台');
  }
  
  // 检查文件大小限制
  if (capabilities.maxImageSize < 10) {
    issues.push(`图片大小限制较小: ${capabilities.maxImageSize}MB`);
    recommendations.push('提供图片压缩功能');
  }
  
  if (capabilities.maxVideoSize < 50) {
    issues.push(`视频大小限制较小: ${capabilities.maxVideoSize}MB`);
    recommendations.push('提供视频压缩或分段上传功能');
  }
  
  return {
    compatible: issues.length === 0,
    issues,
    recommendations
  };
}

// 导出默认实例
export default PlatformManager.getInstance();